/**
 * 头脑风暴会话状态管理
 */
import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import type {
  CreationSession,
  Question,
  Viewpoint,
  MindMapData,
  Outline,
} from '@/types/brainstorm';

interface BrainstormState {
  // State
  currentSession: CreationSession | null;
  sessions: CreationSession[];
  loading: boolean;
  error: string | null;

  // Session Actions
  createSession: (topic: string, hotTopicId?: string, templateId?: string) => void;
  loadSession: (sessionId: string) => Promise<void>;
  updateSession: (updates: Partial<CreationSession>) => void;
  deleteSession: (sessionId: string) => void;
  setCurrentStage: (stage: CreationSession['stage']) => void;

  // Question Actions
  addQuestion: (question: Omit<Question, 'id'>) => void;
  updateQuestion: (questionId: string, updates: Partial<Question>) => void;
  answerQuestion: (questionId: string, answer: string) => void;
  skipQuestion: (questionId: string) => void;

  // Viewpoint Actions
  addViewpoint: (viewpoint: Viewpoint) => void;
  updateViewpoint: (viewpointId: string, updates: Partial<Viewpoint>) => void;
  deleteViewpoint: (viewpointId: string) => void;
  selectViewpoints: (viewpointIds: string[]) => void;
  updateViewpointChunk: (model: string, perspective: string, chunk: string) => void;
  completeViewpoint: (model: string, perspective: string, score: number) => void;

  // MindMap Actions
  updateMindMap: (mindMap: MindMapData) => void;

  // Outline Actions
  setOutline: (outline: Outline) => void;
  updateOutline: (updates: Partial<Outline>) => void;

  // Utility Actions
  reset: () => void;
  setLoading: (loading: boolean) => void;
  setError: (error: string | null) => void;
}

const initialState = {
  currentSession: null,
  sessions: [],
  loading: false,
  error: null,
};

export const useBrainstormStore = create<BrainstormState>()(
  devtools(
    persist(
      (set, get) => ({
        ...initialState,

        // Session Actions
        createSession: (topic, hotTopicId, templateId) => {
          const newSession: CreationSession = {
            id: `session-${Date.now()}`,
            title: `${topic}创作`,
            topic,
            hotTopicId,
            templateId,
            stage: 'brainstorming',
            questions: [],
            viewpoints: [],
            paragraphs: [],
            metadata: {},
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString(),
          };

          set((state) => ({
            currentSession: newSession,
            sessions: [newSession, ...state.sessions],
          }));
        },

        loadSession: async (sessionId) => {
          set({ loading: true, error: null });
          try {
            // TODO: 从API加载会话
            const session = get().sessions.find((s) => s.id === sessionId);
            if (session) {
              set({ currentSession: session, loading: false });
            } else {
              set({ error: '会话不存在', loading: false });
            }
          } catch (error) {
            set({ error: '加载会话失败', loading: false });
          }
        },

        updateSession: (updates) => {
          set((state) => {
            if (!state.currentSession) return state;

            const updatedSession = {
              ...state.currentSession,
              ...updates,
              updatedAt: new Date().toISOString(),
            };

            return {
              currentSession: updatedSession,
              sessions: state.sessions.map((s) =>
                s.id === updatedSession.id ? updatedSession : s
              ),
            };
          });
        },

        deleteSession: (sessionId) => {
          set((state) => ({
            sessions: state.sessions.filter((s) => s.id !== sessionId),
            currentSession:
              state.currentSession?.id === sessionId ? null : state.currentSession,
          }));
        },

        setCurrentStage: (stage) => {
          get().updateSession({ stage });
        },

        // Question Actions
        addQuestion: (question) => {
          set((state) => {
            if (!state.currentSession) return state;

            const newQuestion: Question = {
              ...question,
              id: `question-${Date.now()}`,
            };

            return {
              currentSession: {
                ...state.currentSession,
                questions: [...state.currentSession.questions, newQuestion],
                updatedAt: new Date().toISOString(),
              },
            };
          });
        },

        updateQuestion: (questionId, updates) => {
          set((state) => {
            if (!state.currentSession) return state;

            return {
              currentSession: {
                ...state.currentSession,
                questions: state.currentSession.questions.map((q) =>
                  q.id === questionId ? { ...q, ...updates } : q
                ),
                updatedAt: new Date().toISOString(),
              },
            };
          });
        },

        answerQuestion: (questionId, answer) => {
          get().updateQuestion(questionId, { answer, skipped: false });
        },

        skipQuestion: (questionId) => {
          get().updateQuestion(questionId, { skipped: true });
        },

        // Viewpoint Actions
        addViewpoint: (viewpoint) => {
          set((state) => {
            if (!state.currentSession) return state;

            return {
              currentSession: {
                ...state.currentSession,
                viewpoints: [...state.currentSession.viewpoints, viewpoint],
                updatedAt: new Date().toISOString(),
              },
            };
          });
        },

        updateViewpoint: (viewpointId, updates) => {
          set((state) => {
            if (!state.currentSession) return state;

            return {
              currentSession: {
                ...state.currentSession,
                viewpoints: state.currentSession.viewpoints.map((v) =>
                  v.id === viewpointId ? { ...v, ...updates } : v
                ),
                updatedAt: new Date().toISOString(),
              },
            };
          });
        },

        deleteViewpoint: (viewpointId) => {
          set((state) => {
            if (!state.currentSession) return state;

            return {
              currentSession: {
                ...state.currentSession,
                viewpoints: state.currentSession.viewpoints.filter(
                  (v) => v.id !== viewpointId
                ),
                updatedAt: new Date().toISOString(),
              },
            };
          });
        },

        selectViewpoints: (viewpointIds) => {
          // TODO: 标记选中的观点用于生成提纲
          console.log('Selected viewpoints:', viewpointIds);
        },

        updateViewpointChunk: (model, perspective, chunk) => {
          set((state) => {
            if (!state.currentSession) return state;

            const viewpoint = state.currentSession.viewpoints.find(
              (v) => v.model === model && v.perspective === perspective
            );

            if (viewpoint) {
              viewpoint.content = (viewpoint.content || '') + chunk;
            } else {
              state.currentSession.viewpoints.push({
                id: `${model}-${perspective}`,
                model,
                perspective,
                content: chunk,
                generating: true,
                completed: false,
                coreViewpoint: '',
                arguments: [],
                scenario: '',
                expectedEffect: '',
                aiScore: 0,
                scoreDetails: {
                  relevance: 0,
                  novelty: 0,
                  feasibility: 0,
                  impact: 0,
                },
                createdAt: new Date().toISOString(),
              });
            }

            return {
              currentSession: {
                ...state.currentSession,
                viewpoints: [...state.currentSession.viewpoints],
              },
            };
          });
        },

        completeViewpoint: (model, perspective, score) => {
          set((state) => {
            if (!state.currentSession) return state;

            return {
              currentSession: {
                ...state.currentSession,
                viewpoints: state.currentSession.viewpoints.map((v) => {
                  if (v.model === model && v.perspective === perspective) {
                    try {
                      const parsed = JSON.parse(v.content || '{}');
                      return {
                        ...v,
                        ...parsed,
                        generating: false,
                        completed: true,
                        aiScore: score,
                      };
                    } catch {
                      return { ...v, generating: false, completed: false };
                    }
                  }
                  return v;
                }),
              },
            };
          });
        },

        // MindMap Actions
        updateMindMap: (mindMap) => {
          get().updateSession({ mindMap });
        },

        // Outline Actions
        setOutline: (outline) => {
          get().updateSession({ outline });
        },

        updateOutline: (updates) => {
          set((state) => {
            if (!state.currentSession?.outline) return state;

            return {
              currentSession: {
                ...state.currentSession,
                outline: {
                  ...state.currentSession.outline,
                  ...updates,
                },
              },
            };
          });
        },

        // Utility Actions
        reset: () => set(initialState),

        setLoading: (loading) => set({ loading }),

        setError: (error) => set({ error }),
      }),
      {
        name: 'brainstorm-storage',
        partialize: (state) => ({
          sessions: state.sessions,
          currentSession: state.currentSession,
        }),
      }
    ),
    { name: 'BrainstormStore' }
  )
);
